package com.muyu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.mapper.UserMapper;
import com.muyu.model.bo.UploadFilesBO;
import com.muyu.model.entity.UserEntity;
import com.muyu.service.UserService;
import com.muyu.util.Uploader;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName: FileServiceImpl
 * @Author: Zirun.Xin
 * @Date: 2025/4/24 下午5:28
 * @Version: 1.0
 * @Description: 用户业务实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    /**
     * 用户持久层
     */
    private final UserMapper userMapper;

    /**
     * 件/图片等上传组件
     */
    private final Uploader uploader;

    /**
     * 上传用户头像
     *
     * @param file   文件
     * @param userId 用户标识
     * @return 是否上传成功
     */
    @Override
    public boolean uploadImg(MultipartFile file, Integer userId) {
        // 查询用户信息
        UserEntity userEntity = userMapper.selectById(userId);
        if (Objects.isNull(userEntity)) {
            // 用户不存在 直接返回
            return false;
        }

        // 获取图片及后缀名
        String name = file.getOriginalFilename();
        // 指定文件上传路径
        String targetPath = System.getProperty("user.dir") + "/template/img/" + userId + "/" + name;
        // 文件上传
        try {
            uploader.uploadImage(file, targetPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 用户头像地址修改入库
        userEntity.setImage(targetPath);
        int isUpdateById = userMapper.updateById(userEntity);

        return isUpdateById > 0;
    }

    /**
     * 文件上传（支持批量）
     *
     * @param files 文件集
     * @param type  文件类型
     * @param dfId  主键标识
     * @return 是否上传成功
     */
    @Override
    public boolean uploadFiles(MultipartFile[] files, Integer type, Integer dfId) {
        // 查询用户信息
        UserEntity userEntity = userMapper.selectById(dfId);
        if (Objects.isNull(userEntity)) {
            // 用户不存在 直接返回
            return false;
        }

        List<UploadFilesBO> uploadFilesBOList = new ArrayList<>();

        for (MultipartFile file : files) {
            if (file == null || file.isEmpty()) {
                return false;
            }

            String fileName = Objects.requireNonNull(file.getOriginalFilename());
            // 取文件后缀
            String fileSuffix = fileName.split("\\.")[1];
            if (!Objects.equals(fileSuffix, "jpg")) {
                return false;
            }

            // 指定文件上传路径
            String targetPath = System.getProperty("user.dir") + "/template/img/" + dfId + "/" + fileName;

            // 文件路径存入容器
            uploadFilesBOList.add(UploadFilesBO.builder().file(file).targetPath(targetPath).build());
        }

        // 文件上传
        uploadFilesBOList.forEach(uploadFilesBO -> {
            try {
                uploader.uploadImage(uploadFilesBO.getFile(), uploadFilesBO.getTargetPath());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        // 容器数据路径进行拼接
        List<String> filePathList = uploadFilesBOList.stream()
                .map(UploadFilesBO::getTargetPath).collect(Collectors.toList());
        String filesPath = String.join(",", filePathList);

        //写入数据库
        userEntity.setImage(filesPath);
        int i = userMapper.updateById(userEntity);

        return i > 0;
    }
}
